<?php
require_once 'includes/header.php';
require_once 'includes/DatabaseHelper.php';

require_once 'includes/functions.php';

// 初始化数据库连接
$db = Database::getInstance();

// 检查是否有用户ID
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    $_SESSION['flash_message'] = '无效的用户ID';
    $_SESSION['flash_type'] = 'danger';
    header('Location: users.php');
    exit;
}

$userId = (int)$_GET['id'];

// 获取用户信息
$user = $db->fetchRow("SELECT * FROM " . DB_PREFIX . "users WHERE id = ?", [$userId]);

if (!$user) {
    $_SESSION['flash_message'] = '用户不存在';
    $_SESSION['flash_type'] = 'danger';
    header('Location: users.php');
    exit;
}

// 获取用户游戏记录
$gameRecords = $db->fetchAll("
    SELECT gr.*, g.name as game_name, g.image as game_image
    FROM " . DB_PREFIX . "game_records gr
    JOIN " . DB_PREFIX . "games g ON gr.game_id = g.id
    WHERE gr.user_id = ?
    ORDER BY gr.played_at DESC
    LIMIT 10
", [$userId]);

// 获取用户成就
$achievements = $db->fetchAll("
    SELECT ua.*, a.name as achievement_name, a.description, a.icon, a.points
    FROM " . DB_PREFIX . "user_achievements ua
    JOIN " . DB_PREFIX . "achievements a ON ua.achievement_id = a.id
    WHERE ua.user_id = ?
    ORDER BY ua.unlocked_at DESC
", [$userId]);

// 统计信息
$totalGamesPlayed = $db->fetchColumn("SELECT COUNT(*) FROM " . DB_PREFIX . "game_records WHERE user_id = ?", [$userId]);
$totalAchievements = $db->fetchColumn("SELECT COUNT(*) FROM " . DB_PREFIX . "user_achievements WHERE user_id = ?", [$userId]);
$totalPoints = $db->fetchColumn("
    SELECT SUM(a.points) 
    FROM " . DB_PREFIX . "user_achievements ua
    JOIN " . DB_PREFIX . "achievements a ON ua.achievement_id = a.id
    WHERE ua.user_id = ?
", [$userId]);
$totalPoints = $totalPoints ?: 0;

// 最常玩的游戏
$favoriteGame = $db->fetchRow("
    SELECT g.name, COUNT(*) as play_count
    FROM " . DB_PREFIX . "game_records gr
    JOIN " . DB_PREFIX . "games g ON gr.game_id = g.id
    WHERE gr.user_id = ?
    GROUP BY gr.game_id
    ORDER BY play_count DESC
    LIMIT 1
", [$userId]);

// 最高分数
$highestScore = $db->fetchRow("
    SELECT g.name, gr.score
    FROM " . DB_PREFIX . "game_records gr
    JOIN " . DB_PREFIX . "games g ON gr.game_id = g.id
    WHERE gr.user_id = ?
    ORDER BY gr.score DESC
    LIMIT 1
", [$userId]);

// 上次登录
$lastLogin = !empty($user['last_login']) ? date('Y-m-d H:i', strtotime($user['last_login'])) : '从未登录';

// 注册时长
$registrationDuration = '';
if (!empty($user['created_at'])) {
    $createDate = new DateTime($user['created_at']);
    $now = new DateTime();
    $interval = $createDate->diff($now);
    
    if ($interval->y > 0) {
        $registrationDuration = $interval->y . '年 ' . $interval->m . '个月';
    } elseif ($interval->m > 0) {
        $registrationDuration = $interval->m . '个月 ' . $interval->d . '天';
    } else {
        $registrationDuration = $interval->d . '天';
    }
}
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1><i class="bi bi-person-badge"></i> 用户详情</h1>
    <div>
        <a href="users.php" class="btn btn-outline-secondary me-2">
            <i class="bi bi-arrow-left"></i> 返回用户列表
        </a>
        <a href="user_edit.php?id=<?php echo $user['id']; ?>" class="btn btn-primary">
            <i class="bi bi-pencil"></i> 编辑用户
        </a>
    </div>
</div>

<div class="row">
    <!-- 用户基本信息 -->
    <div class="col-md-4">
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-person-circle"></i> 基本信息
            </div>
            <div class="card-body">
                <div class="text-center mb-4">
                    <?php if (!empty($user['avatar'])): ?>
                        <img src="<?php echo htmlspecialchars($user['avatar']); ?>" alt="用户头像" class="img-fluid rounded-circle mb-3" style="width: 120px; height: 120px;">
                    <?php else: ?>
                        <div class="avatar-placeholder rounded-circle mx-auto mb-3 d-flex align-items-center justify-content-center" style="width: 120px; height: 120px; background-color: #e9ecef;">
                            <i class="bi bi-person display-5"></i>
                        </div>
                    <?php endif; ?>
                    <h3 class="mb-0"><?php echo htmlspecialchars($user['username']); ?></h3>
                    <?php if ($user['role'] == 'admin'): ?>
                        <span class="badge bg-danger">管理员</span>
                    <?php else: ?>
                        <span class="badge bg-info">用户</span>
                    <?php endif; ?>
                    <?php if ($user['status'] == 'active'): ?>
                        <span class="badge bg-success">活跃</span>
                    <?php else: ?>
                        <span class="badge bg-secondary">禁用</span>
                    <?php endif; ?>
                </div>
                
                <div class="mb-3">
                    <label class="form-label fw-bold"><i class="bi bi-envelope"></i> 邮箱：</label>
                    <div><?php echo htmlspecialchars($user['email']); ?></div>
                </div>
                
                <?php if (!empty($user['nickname'])): ?>
                <div class="mb-3">
                    <label class="form-label fw-bold"><i class="bi bi-person-badge"></i> 昵称：</label>
                    <div><?php echo htmlspecialchars($user['nickname']); ?></div>
                </div>
                <?php endif; ?>
                
                <div class="mb-3">
                    <label class="form-label fw-bold"><i class="bi bi-calendar-check"></i> 注册时间：</label>
                    <div><?php echo date('Y-m-d H:i', strtotime($user['created_at'])); ?></div>
                </div>
                
                <div class="mb-3">
                    <label class="form-label fw-bold"><i class="bi bi-clock-history"></i> 注册时长：</label>
                    <div><?php echo $registrationDuration; ?></div>
                </div>
                
                <div class="mb-3">
                    <label class="form-label fw-bold"><i class="bi bi-box-arrow-in-right"></i> 上次登录：</label>
                    <div><?php echo $lastLogin; ?></div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 用户统计数据 -->
    <div class="col-md-8">
        <div class="row">
            <!-- 统计卡片 -->
            <div class="col-md-4 mb-4">
                <div class="card bg-primary text-white h-100">
                    <div class="card-body">
                        <h5 class="card-title"><i class="bi bi-controller"></i> 游戏次数</h5>
                        <h2 class="display-4"><?php echo number_format($totalGamesPlayed); ?></h2>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4 mb-4">
                <div class="card bg-success text-white h-100">
                    <div class="card-body">
                        <h5 class="card-title"><i class="bi bi-trophy"></i> 成就数量</h5>
                        <h2 class="display-4"><?php echo number_format($totalAchievements); ?></h2>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4 mb-4">
                <div class="card bg-info text-white h-100">
                    <div class="card-body">
                        <h5 class="card-title"><i class="bi bi-star"></i> 总积分</h5>
                        <h2 class="display-4"><?php echo number_format($totalPoints); ?></h2>
                    </div>
                </div>
            </div>
            
            <!-- 游戏偏好 -->
            <div class="col-md-12 mb-4">
                <div class="card">
                    <div class="card-header">
                        <i class="bi bi-graph-up"></i> 用户统计
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="fw-bold">最常玩的游戏：</label>
                                    <div>
                                        <?php if ($favoriteGame): ?>
                                            <?php echo htmlspecialchars($favoriteGame['name']); ?> (<?php echo $favoriteGame['play_count']; ?>次)
                                        <?php else: ?>
                                            暂无数据
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="fw-bold">最高分数：</label>
                                    <div>
                                        <?php if ($highestScore): ?>
                                            <?php echo htmlspecialchars($highestScore['name']); ?> (<?php echo $highestScore['score']; ?>分)
                                        <?php else: ?>
                                            暂无数据
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="fw-bold">最后一次游戏：</label>
                                    <div>
                                        <?php if (!empty($gameRecords)): ?>
                                            <?php echo htmlspecialchars($gameRecords[0]['game_name']); ?> 
                                            (<?php echo date('Y-m-d H:i', strtotime($gameRecords[0]['played_at'])); ?>)
                                        <?php else: ?>
                                            暂无数据
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="fw-bold">本月游戏次数：</label>
                                    <?php 
                                    $monthlyGames = $db->fetchColumn("
                                        SELECT COUNT(*) FROM " . DB_PREFIX . "game_records 
                                        WHERE user_id = ? AND MONTH(played_at) = MONTH(CURRENT_DATE()) 
                                        AND YEAR(played_at) = YEAR(CURRENT_DATE())
                                    ", [$userId]);
                                    ?>
                                    <div><?php echo $monthlyGames; ?>次</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 用户成就 -->
            <div class="col-md-12 mb-4">
                <div class="card">
                    <div class="card-header">
                        <i class="bi bi-trophy"></i> 用户成就
                    </div>
                    <div class="card-body">
                        <?php if (!empty($achievements)): ?>
                            <div class="row">
                                <?php foreach ($achievements as $achievement): ?>
                                    <div class="col-md-6 mb-3">
                                        <div class="d-flex align-items-center">
                                            <div class="flex-shrink-0">
                                                <?php if (!empty($achievement['icon'])): ?>
                                                    <img src="<?php echo htmlspecialchars($achievement['icon']); ?>" alt="成就图标" class="rounded" width="50" height="50">
                                                <?php else: ?>
                                                    <div class="bg-light rounded d-flex align-items-center justify-content-center" style="width: 50px; height: 50px;">
                                                        <i class="bi bi-trophy text-warning"></i>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                            <div class="flex-grow-1 ms-3">
                                                <h5 class="mb-0"><?php echo htmlspecialchars($achievement['achievement_name']); ?></h5>
                                                <p class="text-muted mb-0">
                                                    <?php echo htmlspecialchars($achievement['description']); ?> 
                                                    <span class="badge bg-warning text-dark"><?php echo $achievement['points']; ?> 分</span>
                                                </p>
                                                <small class="text-muted">
                                                    解锁于 <?php echo date('Y-m-d H:i', strtotime($achievement['unlocked_at'])); ?>
                                                </small>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            <?php if (count($achievements) >= 10): ?>
                                <div class="text-center mt-3">
                                    <a href="user_achievements.php?id=<?php echo $userId; ?>" class="btn btn-outline-primary">
                                        查看所有成就
                                    </a>
                                </div>
                            <?php endif; ?>
                        <?php else: ?>
                            <div class="alert alert-info">
                                该用户尚未获得任何成就。
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <!-- 最近游戏记录 -->
            <div class="col-md-12 mb-4">
                <div class="card">
                    <div class="card-header">
                        <i class="bi bi-controller"></i> 最近游戏记录
                    </div>
                    <div class="card-body">
                        <?php if (!empty($gameRecords)): ?>
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>游戏</th>
                                            <th>得分</th>
                                            <th>时长</th>
                                            <th>游戏时间</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($gameRecords as $record): ?>
                                            <tr>
                                                <td>
                                                    <div class="d-flex align-items-center">
                                                        <?php if (!empty($record['game_image'])): ?>
                                                            <img src="<?php echo htmlspecialchars($record['game_image']); ?>" alt="游戏图片" class="img-thumbnail me-2" width="40">
                                                        <?php else: ?>
                                                            <div class="bg-light rounded d-flex align-items-center justify-content-center me-2" style="width: 40px; height: 40px;">
                                                                <i class="bi bi-controller"></i>
                                                            </div>
                                                        <?php endif; ?>
                                                        <?php echo htmlspecialchars($record['game_name']); ?>
                                                    </div>
                                                </td>
                                                <td>
                                                    <span class="badge bg-<?php echo $record['score'] > 80 ? 'success' : ($record['score'] > 50 ? 'warning' : 'danger'); ?>">
                                                        <?php echo $record['score']; ?> 分
                                                    </span>
                                                </td>
                                                <td>
                                                    <?php if ($record['duration']): ?>
                                                        <?php 
                                                        $minutes = floor($record['duration'] / 60);
                                                        $seconds = $record['duration'] % 60;
                                                        echo $minutes > 0 ? $minutes . '分' . $seconds . '秒' : $seconds . '秒';
                                                        ?>
                                                    <?php else: ?>
                                                        -
                                                    <?php endif; ?>
                                                </td>
                                                <td><?php echo date('Y-m-d H:i', strtotime($record['played_at'])); ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            <?php if (count($gameRecords) >= 10): ?>
                                <div class="text-center">
                                    <a href="user_game_records.php?id=<?php echo $userId; ?>" class="btn btn-outline-primary">
                                        查看所有游戏记录
                                    </a>
                                </div>
                            <?php endif; ?>
                        <?php else: ?>
                            <div class="alert alert-info">
                                该用户尚未玩过任何游戏。
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php require_once 'includes/footer.php'; ?> 